<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js加载</title>
</head>
<body>
    <h1>Node.js加载</h1>
    <h2>Node.js对ES6模块的处理</h2>

    <script type="module">
        // ES6模块的两种引入方式
        // 1. 文件后缀名为.mjs
        // foo.mjs
        export function foo() {
            console.log('foo');
        }

        // 2. package.json指定type: "module"
        /*
        {
            "type": "module"
        }
        */

        // Node.js中的main字段
        /*
        {
            "main": "./src/index.js",
            "exports": {
                ".": "./src/index.js",
                "./features": "./src/features/index.js"
            }
        }
        */

        // 条件加载
        /*
        {
            "exports": {
                "import": "./index-module.js",
                "require": "./index-require.cjs"
            }
        }
        */

        // 同时支持ESM和CommonJS的模块
        // 入口文件 index.js
        export function add(a, b) {
            return a + b;
        }

        // CommonJS入口 index.cjs
        function add(a, b) {
            return a + b;
        }
        module.exports = { add };

        // package.json
        /*
        {
            "type": "module",
            "exports": {
                "import": "./index.js",
                "require": "./index.cjs"
            }
        }
        */

        // 实际应用示例
        // utils/math.mjs
        export const add = (a, b) => a + b;
        export const multiply = (a, b) => a * b;

        // utils/logger.mjs
        export class Logger {
            log(message) {
                console.log(`[${new Date().toISOString()}] ${message}`);
            }
        }

        // main.mjs
        import { add, multiply } from './utils/math.mjs';
        import { Logger } from './utils/logger.mjs';

        const logger = new Logger();
        logger.log(`计算结果: ${add(2, 3)}`);
        logger.log(`计算结果: ${multiply(4, 5)}`);
    </script>
</body>
</html> 